<?php


namespace api\web\controller;


use api\web\model\OrderModel;
use api\web\model\UserModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class PayController extends RestBaseController
{
    //账户余额支付
    public function walletPay(Request $request)
    {
        $orderId = input('post.order_id');
        $order = OrderModel::find($orderId);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order['status'] != 0) {
            $this->error('该订单已支付');
        }
        //查询用户
        $user = UserModel::find($request->userId);
        //判断账户余额是否够
        if ($user['money'] < $order['total_price']) {
            $this->error('账户余额不足');
        }
        Db::startTrans();
        $updateOrderStatus = false;
        $addMonerLog = false;
        $updateUserMoney = false;
        try {
            //1.订单的status修改成1
            $order->status = 1;
            $order->pay_type = '账户余额';
            $updateOrderStatus = $order->save();
            //2、流水记录
            $addMonerLog = add_money_log($order['user_id'], $order['total_price'], '购买商品', 0);
            //3.用户余额修改
            $user->money = $user['money'] - $order['total_price'];
            $updateUserMoney = $user->save();

        } catch (\Exception $exception) {

            $this->error($exception->getMessage());
            Db::rollback();
        }
        if ($updateOrderStatus && $addMonerLog && $updateUserMoney) {
            Db::commit();
            return json(['status' => 'success', 'message' => '充值成功',]);
        } else {
            Db::rollback();
            $this->error('支付失败');
        }
    }

}